#include "publishres.h"
#include <QMessageBox>

extern void msgBox(QWidget *parent, QMessageBox::Icon icon,QString title, QString msg);
extern QString getTime(QDateTime d);

PublishRes::PublishRes(QWidget *parent) : QWidget(parent)
{
    QVBoxLayout *vLayout = new QVBoxLayout();
    //vLayout->setMargin(0);
    QHBoxLayout *hLayout = new QHBoxLayout();
    hLayout->setMargin(0);

    QLabel *label1 = new QLabel("请输入资源描述，尽量详细一点");
    vLayout->addWidget(label1);

    textContent = new QTextEdit();
    textContent->setMinimumHeight(100);
    vLayout->addWidget(textContent);

    QWidget *widget = new QWidget();
    QList<QString> strList;
    strList << "C" << "C++" << "PHP" << "Java" << "Android" << "HmarmonyOS" << "STM32";
    comboBoxType = new QComboBox();
    connect(comboBoxType, SIGNAL(currentIndexChanged(int)), SLOT(slotSetType(int)));
    for(int i=0; i<strList.length(); i++)
    {
       comboBoxType->addItem(strList.at(i));
    }
    hLayout->addWidget(comboBoxType);
    comboBoxPay = new QComboBox();
    comboBoxPay->addItem("免费");
    comboBoxPay->addItem("付费");
    connect(comboBoxPay, SIGNAL(currentIndexChanged(int)), SLOT(slotSetPay(int)));
    hLayout->addWidget(comboBoxPay);
    btnSelect = new QPushButton("请选择文件");
    connect(btnSelect, SIGNAL(clicked()), this, SLOT(slotBtnSelectRes()));
    hLayout->addWidget(btnSelect);
    btnPublish = new QPushButton("上传资源");
    connect(btnPublish, SIGNAL(clicked()), this, SLOT(slotBtnPublishRes()));
    hLayout->addWidget(btnPublish);

    widget->setLayout(hLayout);
    vLayout->addWidget(widget);
    setLayout(vLayout);
}

void PublishRes::slotBtnSelectRes()
{
    // 选择文件
    fileName = QFileDialog::getOpenFileName(this, tr("打开文件"), "/", tr("图片(*.tar *.rar *.zip *.bz2 *.gz)"));

    QFile *tmpFile = new QFile(fileName);
    if(!tmpFile->open(QFile::ReadOnly))
    {
        qDebug() << "open file error!";
        return;
    }
    //文件总大小
    fileSize = tmpFile->size();
}

void PublishRes::slotBtnPublishRes()
{
    fileContent = textContent->toPlainText();
    if(fileContent.length() < 10)
    {
        msgBox(this, QMessageBox::Warning, "警告", "请输入大于10个字符的文件描述信息");
    }
    else
    {
        if(fileName!=nullptr)
        {
            QMap<QString, QString> map;
            map.insert("file_name", fileName);
            map.insert("file_size", QString::number(fileSize));
            map.insert("file_title", textContent->toPlainText());
            map.insert("file_type", comboBoxType->currentText());
            map.insert("file_pay", comboBoxPay->currentText());
            emit signalPublishRes(map);
        }
    }
}

void PublishRes::slotSetPay(int pay)
{
    this->isPay = pay;
}

void PublishRes::slotSetType(int idx)
{
    this->fileType = comboBoxType->currentText();
}
